<template>
  <div>
    <div class="container">
      <div class="AddAddress" @click="addOrUpdate(0, null)">
        新增收货地址
      </div>

      <div v-if="addressList.length == 0">
        <el-empty
            image="https://shyvv-1308916267.cos.ap-chengdu.myqcloud.com/mall/58881654671202045.png"
            :image-size="500"
            description="快去添加收货地址吧!"/>
      </div>

      <div>
        <div class="Address" v-for="(item, index) in addressList" :key="item.id" v-if="addressList.length != 0">
          <div class="top">
            <span style="float: right; padding-right: 20px;">
              设置默认地址
              <el-switch v-model="item.defaultStatus" active-color="#07a0ff" inactive-color="#efefef"
                         :active-value="1" :inactive-value="0" @change="updateDefault(item, $event)"/>
            </span>
          </div>
          <div class="conter">
            <p>收件人：{{ item.name }}</p>
            <p>所在地区：{{ item.province + item.city + item.region }}</p>
            <p>详细地址：{{ item.detailAddress }}</p>
            <p>手机号：{{ item.phoneNumber }}</p>
          </div>

          <div class="footers">
            <div class="left">
              <div style="cursor: pointer;" @click="showDel(item.id)">
                <el-icon>
                  <DeleteFilled/>
                </el-icon>
                <span style="position: relative; top: -2px;">
                  删除
                </span>
              </div>
            </div>
            <div class="right">
              <div style="cursor: pointer; " @click="addOrUpdate(1, item)">
                <el-icon>
                  <EditPen/>
                </el-icon>
                <span style="position: relative; top: -2px;">
                  修改
                  <div class="icon" v-if="item.defaultStatus==1">

                  </div>
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 显示删除 -->
    <CustomModal :visible.sync="delShow" :title="title" @confirm="deleteAddress(DelList)">
      <div class="conter" style="text-align: center;">
        <p>收件人：{{ DelList.name }}</p>
        <p>所在地区：{{ DelList.province + DelList.city + DelList.region }}</p>
        <p>详细地址：{{ DelList.detailAddress }}</p>
        <p>手机号：{{ DelList.phoneNumber }}</p>
      </div>
    </CustomModal>

    <!-- 显示添加或者修改 -->
    <CustomModal :visible.sync="ShowaddRoUpdate" :title="title" @confirm="adOrUpdate">
      <el-form :model="form" label-width="120px">
        <el-form-item label="所在地区:">
          <el-cascader v-model="district" separator="-" :options="options" :props="optionProps"
                       style="width: 350px;" @change="handleChange"/>
        </el-form-item>

        <el-form-item label="详细地址:">
          <el-input style="width: 350px;" v-model="form.detailAddress"></el-input>
        </el-form-item>

        <el-form-item label="收件人姓名:">
          <el-input style="width: 350px;" v-model="form.name"></el-input>
        </el-form-item>

        <el-form-item label="手机号:">
          <el-input style="width: 350px;" v-model="form.phoneNumber"></el-input>
        </el-form-item>

        <el-form-item label="邮政编号:">
          <el-input style="width: 350px;" v-model="form.postCode"></el-input>
        </el-form-item>

        <el-form-item label="">
          <el-checkbox v-model="defaultstatu" label="设为默认地址" size="large"/>
        </el-form-item>

      </el-form>
    </CustomModal>
  </div>
</template>

<script>
import {Message} from 'element-ui';
import CustomModal from '@/components/CustomModal';
import {addAddress, getAddressById, getUserAddress} from "@/api/address/address";

export default {
  components: {CustomModal},
  data() {
    return {
      addressList: [],
      delShow: false,
      DelList: {},
      ShowaddRoUpdate: false,
      type: 0, // 0 for add, 1 for update
      title: '添加地址',
      form: {
        city: "",
        defaultStatus: 0,
        detailAddress: "",
        id: 0,
        memberId: 0,
        name: "",
        phoneNumber: "", // 确保这里有默认值
        postCode: "",
        province: "",
        region: ""
      },
      UPdateList: {
        city: "",
        defaultStatus: 0,
        detailAddress: "",
        id: 0,
        memberId: 0,
        name: "",
        phoneNumber: "", // 确保这里有默认值
        postCode: "",
        province: "",
        region: ""
      },
      district: [],
      options: [],
      optionProps: {
        value: "name",
        label: "name",
        children: "children",
      },
      defaultstatu: false,
      area: ""
    };
  },
  created() {
    this.getAddress()
    this.getUserAddress()
  },
  methods: {
    getDefaultAddress() {
      let from = {}
      this.addressList.forEach(item => {
        if (item.defaultStatus == 1) {
          from = item
        }
      })
      return from;
    },
    getUserAddress() {
      this.$api.address.getUserAddress().then((res) => {
        if (res.code == 200) {
          this.addressList = res.data;
        }
      });
    },
    filterOptions(options) {
      return options.filter(option => {
        if (option.children) {
          // 递归处理子级
          option.children = this.filterOptions(option.children);
          // 如果处理后的子级为空，则直接删除children属性
          if (option.children.length === 0) {
            delete option.children;
          }
        }
        // 保留有子级或本身没有子级的节点
        return !option.children || option.children.length > 0;
      });
    },
    getAddress() {
      this.$api.common.getAddress().then((res) => {
        if (res.code == 200) {
          this.options = this.filterOptions(res.data)
        }
      });
    },
    updateDefault(item, state) {
      this.$api.address.updateAddress(item.id, item).then(res => {
        if (res.code == 200) {
          Message.success("修改成功~");
          this.getUserAddress()
        }
      })
    },
    showDel(id) {
      this.DelList = this.addressList.find(addr => addr.id === id) || {};
      this.delShow = true;
    },
    deleteAddress(item) {
      this.$api.address.deleteAddress(item.id).then(res => {
        if (res.code == 200) {
          Message.success("删除成功~");
          this.delShow = false;
          this.getUserAddress()
        }
      })
    },
    addOrUpdate(type, item) {
      this.type = type;
      if (type == 1) {
        this.title = '修改地址';
        this.$api.address.getAddressById(item.id).then(res => {
          if (res.code == 200) {
            this.form = res.data
            this.defaultstatu = res.data.defaultStatus ? true : false
            this.district = [
              this.form.province,
              this.form.city,
              this.form.region || '' // 如果 region 不存在，设置为空字符串
            ].filter(item => item !== ''); // 过滤掉空字符串
          }
        })
      } else {
        this.title = '添加地址';
        this.clear();
      }
      this.ShowaddRoUpdate = true;
    },
    clear() {
      this.form = Object.assign(this._data.form, this.$options.data().form)
      this.district = [];
      this.defaultstatu = false;
      this.area = "";
    },
    handleChange(arr) {
      this.area = `${arr[0]}-${arr[1]}-${arr[2]}`;
    },
    adOrUpdate() {
      let formToSubmit = this.form;
      if (this.district.length == 0) {
        Message.warning("地区不能为空~");
        return;
      } else if (formToSubmit.detailAddress == "") {
        Message.warning("详细地址不能为空~");
        return;
      } else if (formToSubmit.name == "") {
        Message.warning("收件人不能为空~");
        return;
      } else if (formToSubmit.postCode == "") {
        Message.warning("邮政编码不能为空~");
        return;
      } else if (formToSubmit.phoneNumber == "") {
        Message.warning("手机号不能为空~");
        return;
      }

      let reg = /^1[13456789]\d{9}$/;
      if (!reg.test(formToSubmit.phoneNumber)) {
        Message.warning("手机号格式不正确~");
        return;
      }

      let arr = [];
      if (this.type == 0) {
        arr = this.area.split('-');
      } else {
        arr = this.district
      }
      if (arr[2] == "undefined") { //说明 区没有
        formToSubmit.province = arr[0];
        formToSubmit.city = arr[1];
      } else {
        formToSubmit.province = arr[0];
        formToSubmit.city = arr[1];
        formToSubmit.region = arr[2];
      }
      if (this.defaultstatu) {
        formToSubmit.defaultStatus = 1;
      } else {
        formToSubmit.defaultStatus = 0;
      }
      if (this.type == 1) {
        this.$api.address.updateAddress(this.form.id, formToSubmit).then(res => {
          if (res.code == 200) {
            Message.success("修改成功~");
            this.getUserAddress()
          }
        })
      } else {
        // formToSubmit.id = this.addressList.length + 1;
        this.$api.address.addAddress(formToSubmit).then(res => {
          if (res.code == 200) {
            Message.success("添加成功~");
            this.getUserAddress()
          }
        })
      }
      this.ShowaddRoUpdate = false;
    }
  }
};
</script>

<style scoped>
/*.container {*/
/*  width: 1088px;*/
/*  height: 100%;*/
/*  border-left: 1px solid gainsboro;*/
/*}*/

.AddAddress {
  text-align: center;
  margin: 20px 10px 0px 20px;
  width: 100px;
  height: 40px;
  color: #0368F9;
  line-height: 40px;
  font-size: 15px;
  border: 1px solid #0368F9;
  cursor: pointer;
}

.Address {
  width: 462px;
  border: 1px solid gainsboro;
  height: 280px;
  float: left;
  box-sizing: border-box;
  margin-left: 20px;
  margin-top: 20px;
}

.Address:nth-child(even) {
  margin-left: 30px;
}

.top {
  height: 40px;
  line-height: 40px;
  font-size: 15px;
}

.conter {
  height: 140px;
  font-size: 15px;
  padding: 20px;
  padding-left: 30px;
}

.conter p {
  margin: 10px 0;
}

.footers {
  width: 100%;
  line-height: 57px;
  text-align: center;
  border-top: 1px solid gainsboro;
  height: 57px;
  font-size: 20px;
}

.left {
  width: 50%;
  height: 100%;
  float: left;
  border-right: 1px solid gainsboro;
}

.right {
  width: 49%;
  height: 100%;
  margin: 0 -8px;
  float: right;
}

.icon {
  position: absolute;
  top: -15px;
  bottom: 0;
  right: -82px;
  height: 59px;
  width: 59px;
  background: url(../../assets/icon.png);
  overflow: hidden;
}

/deep/ .el-dialog__wrapper {
  z-index: 10000;
}
</style>